<?php
//购物车
class App_Cart extends Data_Base
{
	//购物车信息
    public static function detailList ($user)
    {
        $uid = $user->getUserUid();
        if ($uid == 0)
            return array();

        $query = DB::select()
            ->from('app_cart')
            ->where('uid', '=', $uid)
            ->order_by('changed', 'desc')
            ->execute();

        $ret = array();
        foreach ($query as $rs)
        {
            $goods = App_Goods::basicInfo($rs['goodsId'], $rs['goodsAttrId'], $rs['quantity']);
            $shopId = Arr::get($goods, 'shopId');
            if (! array_key_exists ($shopId, $ret))
            {
                $ret[$shopId] = array(
                    'shop' => App_Shop::basicInfo($shopId, FALSE),
                    'goods' => array(),
                );
            }
            $goods['cartId']  = $rs['id'];
            $goods['created'] = $rs['created'];
            $goods['changed'] = $rs['changed'];
            $goods['goodsId'] = $rs['goodsId'];
            $goods['quantity']= $goods['money']['quantity'];
            $ret[$shopId]['goods'][] = $goods;
        }

        return $ret;
    }

	//移除购物车
    public static function remove ($user, $arrCartIds)
    {
        if (empty($arrCartIds))
            return FALSE;

        $rows = DB::delete('app_cart')
            ->where('uid', '=', $user->getUserUid())
            ->where('id', 'in', $arrCartIds)
            ->execute();

        return $rows;
    }

	//添加购物车
    public static function add ($goodsId, $goodsAttrId, $count)
    {
        $uid = User::currentUser()->getUserUid();

        if ($uid == 0)
            return FALSE;

        $query = DB::select('id')
            ->from('app_cart')
            ->where('uid', '=', $uid)
            ->where('goodsId', '=', $goodsId)
            ->where('goodsAttrId', '=', $goodsAttrId)
            ->execute();

        if ($query->count() > 0)
        {
            $current = $query->current();
            $id = $current['id'];
            $query = DB::update('app_cart')
                ->set(array('quantity' => DB::expr("`quantity` + $count"),
                        'changed' => DB::expr('unix_timestamp(now())')
                    ))
                ->where('id', '=', $id)
                ->execute();
        }
        else
        {
            $row = array(
                'goodsId' => $goodsId,
                'goodsAttrId' => $goodsAttrId,
                'quantity' => $count,
                'uid'      => $uid,
                'created'  => DB::expr('unix_timestamp(now())'),
                'changed'  => DB::expr('unix_timestamp(now())'),
            );

            list($insert_id, $rows) = DB::insert('app_cart')
                ->columns (array_keys($row))
                ->values (array_values($row))
                ->execute();
        }

        return TRUE;
    }
}
